<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="关键字" prop="name" label-width="68px">
        <el-input v-model="queryParams.name" placeholder="商品名称、场馆名称、商品编号" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="归属场馆" prop="artVenues">
        <el-select v-model="queryParams.artVenues" placeholder="场馆选择" clearable filterable style="width: 240px">
          <el-option v-for="dict in this.lotVenueList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否上架" prop="isPutaway">
        <el-select v-model="queryParams.isPutaway" clearable style="width: 240px">
          <el-option v-for="dict in this.putawayStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否兑换" prop="artConvertState">
        <el-select v-model="queryParams.artConvertState" clearable style="width: 140px">
          <el-option v-for="dict in this.artConvertState" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="价格区间" prop="startPrice">
        <el-input v-model="queryParams.startPrice" placeholder="开始价格" clearable style="width: 113px" />
        -
        <el-input v-model="queryParams.endPrice" placeholder="结束价格" clearable style="width: 113px" />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="createDateRange" style="width: 340px" type="datetimerange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" value-format="yyyy-MM-dd HH:mm:ss">
          ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['showroom:art:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="this.queryParams.isPutaway == 0" type="success" plain size="mini" @click="changeLotStatus" v-hasPermi="['showroom:art:batchUp']">一键上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-if="this.queryParams.isPutaway == 1" type="danger" plain size="mini" @click="changeLotStatus" v-hasPermi="['showroom:art:batchUp']">一键下架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="exportExcel" v-hasPermi="['showroom:art:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :height="tableHeight" ref="elTable" @sort-change="changeTableSort" v-loading="loading" :data="goodsList" :row-key="getRowKeys" @selection-change="handleSelectionChange" @row-dblclick="handleUpdate" stripe border>
      <el-table-column v-if="this.queryParams.isPutaway" type="selection" :reserve-selection="reSelect" width="55" align="center">
      </el-table-column>
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="商品名称" prop="name" width="200" :sortable="'custom'" />
      <el-table-column label="商品编号" prop="goodsNo" width="150" align="center" :sortable="'custom'" />
      <el-table-column label="归属场馆" prop="artVenueName" width="150" align="center" />
      <el-table-column label="成本价(元)" :sortable="'custom'" prop="costPrice" width="120" align="center" v-if="checkPermi(['showroom:art:lookprice'])" />
      <el-table-column label="现金价格(元)" :sortable="'custom'" prop="cashPrice" width="120" align="center" />
      <el-table-column label="金积分价格" :sortable="'custom'" prop="goldPrice" width="120" align="center" />
      <el-table-column label="银积分价格" :sortable="'custom'" prop="silverPrice" width="120" align="center" />
      <el-table-column label="止售次数" prop="resellNum" width="100" align="center" :sortable="'custom'" />
      <el-table-column label="是否上架" prop="isPutaway" align="center" width="120" :sortable="'custom'">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_putaway_status" :value="scope.row.isPutaway" />
        </template>
      </el-table-column>
      <el-table-column label="兑换状态" prop="artConvertState" width="120" align="center" :sortable="'custom'">
        <template slot-scope="scope">
          {{selectDictLabel(artConvertState,scope.row.artConvertState)}}
        </template>
      </el-table-column>
      <el-table-column label="缩略图" prop="imgMin" align="center" width="150">
        <template slot-scope="scope">
          <table-image :imgDicUrls="scope.row.imgMin"></table-image>
        </template>
      </el-table-column>
      <el-table-column label="大图" prop="minList" align="center" width="150">
        <template slot-scope="scope">
          <table-image :imgDicUrls="scope.row.minList"></table-image>
        </template>
      </el-table-column>
      <el-table-column label="排序" sortable prop="orderNum" width="80" align="center" />
      <el-table-column label="创建时间" sortable prop="createTime" align="center" min-width="160" />
      <el-table-column label="操作" fixed="right" align="center" width="180">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isPutaway == 1" size="mini" type="text" icon="" @click.stop="batchUp(scope.row)" v-hasPermi="['showroom:art:batchUp']">下架</el-button>
          <div v-else>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['showroom:art:edit']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="copyGoods(scope.row)" v-hasPermi="['showroom:art:edit']">复制商品</el-button>

            <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDelete(scope.row)" v-hasPermi="['showroom:art:remove']">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-row type="flex" class="row-bg" justify="space-between">
      <el-col :span="4">
        <span v-if="this.queryParams.isPutaway !== undefined" style="line-height:60px">已选中:{{this.batchUpParams.ids.length}}</span>
      </el-col>
      <el-col :span="16">
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 新建竞价品 -->
    <div v-if="open">
      <Z-Dialog :title="title" :visible.sync="open" @confirm="submitForm('formView')" @cancel="open=false">
        <form-view :formData="form" :lotVenueList="lotVenueList" :venueList="venueList" ref="formView"></form-view>
      </Z-Dialog>
    </div>

  </div>
</template>

<script>
import { listGoodsInfo, addGoodsInfo, batchUpGoodsInfo, editGoodsInfo, delGoodsInfo } from "@/api/showroom/goods";
import { listVenue } from "@/api/showroom/venue";
import tableImage from "@/components/TableImageView/index.vue";
import { goodsPayTypeEnum } from '@/common/enums'
import { excelExportApi } from '@/api/filer'
import formView from "./formView.vue";
import { deepClone } from '@/utils/index'
import { checkPermi } from "@/utils/permission"; // 权限判断函数
import hasPer from "@/directive/permission/hasPer.js";
import { Row } from 'element-ui';
import { getDateTime, compare } from "@/utils/index"

export default {
  name: "Art", //兑换商品
  components: { tableImage, formView },
  dicts: [
    "goods_isResell_status",
    "goods_putaway_status",
  ],
  data() {
    return {
      goodsPayTypeEnum,
      //是否显示止售日期搜索框
      isShowDate: false,
      reSelect: true,
      //上传的图片
      dialogImageUrl: "",
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      goodsList: [], //商品列表
      venueList: [], //场馆列表
      dateRange: [], //日期区间
      createDateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否显示添加弹窗
      add_open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: this.global.pageSize,
        typeCode: 4,
        name: undefined,
        resellStatus: undefined,
        isPutaway: undefined,
        startPrice: undefined,
        endPrice: undefined,
        isResell: undefined,
        venueId: undefined
      },
      pageNum: 1,
      // 表单参数
      form: {},

      typeList: [
        { label: "竞价品", value: 1 },
        { label: "兑换商品", value: 4 },
      ],

      artConvertState: [
        { label: "全部", value: null },
        { label: "未兑换", value: 0 },
        { label: "已兑换", value: 1 },
      ],

      resellStatus: [
        { label: "止售区", value: "zp" },
        { label: "非止售区", value: "fzp" },
      ],

      batchUpParams: {
        ids: [],
        isPutaway: undefined
      },

      lotVenueList: [],
    };
  },
  watch: {
    "queryParams.resellStatus": {
      deep: true,
      handler: function (newV, oldV) {
        this.isShowDate = newV == "zp" ? true : false;
      },
    },
    "queryParams.isPutaway": {
      deep: true,
      handler: function (newV, oldV) {
        this.batchUpParams.isPutaway = newV == 1 ? 0 : 1; //上下架取反
        this.batchUpParams.ids = [];
      },
    },

    "queryParams": {
      deep: true,
      handler: function (newV, oldV) {
        if (this.pageNum == newV.pageNum) {
          this.handleQuery();
        } else {
          this.pageNum = newV.pageNum;
        }
      },
    },
    createDateRange(newV, oldV) {
      if (newV) {
        if (newV.length >= 2) {
          this.queryParams.createTimeStart = String(newV[0]);
          this.queryParams.createTimeEnd = String(newV[1]);
        }
      } else {
        this.queryParams.createTimeStart = undefined;
        this.queryParams.createTimeEnd = undefined;
      }
      this.getList();
    },
  },
  computed: {
    tableHeight() {
      return 'calc(100vh - 330px)'
    },
    //状态列表添加全部
    goodsTypeList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.typeList));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //转售状态添加全部
    resellAllList() {
      let typeDictArray = JSON.parse(
        JSON.stringify(this.dict.type.goods_isResell_status)
      );
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //止售区域状态
    resellStatusList() {
      let typeDictArray = JSON.parse(JSON.stringify(this.resellStatus));
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
    //上架状态
    putawayStatusList() {
      let typeDictArray = JSON.parse(
        JSON.stringify(this.dict.type.goods_putaway_status)
      );
      typeDictArray.unshift({ label: "全部", value: undefined });
      return typeDictArray;
    },
  },
  created() {
    this.getList();
    this.getVenueList();
  },
  methods: {
    checkPermi,
    getList() {
      this.loading = true;
      listGoodsInfo(this.queryParams)
        .then((response) => {
          if (response.code == 200) {
            this.goodsList = response.data;
            this.total = response.total;
          }
          this.loading = false;
          this.reSelect = true;
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    changeTableSort(column) {
      this.queryParams.orderBy = column.prop;
      this.queryParams.isAsc = (column.order == 'descending' ? 0 : 1); //ascending == 升序 descending == 降序  0 倒,1正
      this.getList();
    },

    //复制商品
    copyGoods(row) {
      this.$store.commit('SETCOPYGOODS', {
        name: row.name,
        minList: row.minList,
        details: row.details
      })
      this.$modal.msgSuccess("复制成功");
    },

    /**获取场馆列表 */
    getVenueList() {
      listVenue(this.queryParams)
        .then((response) => {
          if (response.code == 200) {
            this.venueList = response.data;
            // this.venueList.sort(compare('id', true));
            this.lotVenueList = this.venueList.filter((item, index, arr) => {
              return item.venueType == 0;
            })
            this.lotVenueList.push({"id":0,"name":"随机分配场馆","venueType":0})
          }
        })
        .catch((err) => { });
    },

    //列表选中
    handleSelectionChange(val) {
      this.batchUpParams.ids = val.map(item => {
        return item.id;
      })
    },

    getRowKeys(row) {
      return row.id
    },

    //下架
    batchUp(row) {
      this.batchUpParams.ids = [row.id];
      this.batchUpParams.isPutaway = 0;
      this.$modal
        .confirm('是否确认下架商品编号"' + row.goodsNo + '的商品"？')
        .then(() => {
          this.changeLotStatus();
        }
        );
    },

    /**一键上下架 */
    changeLotStatus() {
      if (!this.batchUpParams.ids) {
        this.$modal.msgError("请选择需要操作的商品");
        return;
      }
      batchUpGoodsInfo(this.batchUpParams).then((response) => {
        this.$modal.msgSuccess("操作成功");
        this.queryParams.isPutaway = undefined;
        this.batchUpParams.ids = [];
        this.$refs.elTable.clearSelection();
        this.reSelect = false;
        this.getList();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      // this.resetForm("form");
      this.form = {};
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.endPrice = undefined;
      this.queryParams.createDateRange = undefined;
      this.queryParams.createTimeStart = undefined;
      this.createDateRange = undefined;
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },

    /**上传数据 */
    uploaded(params, dict) {
      this.form[params] = JSON.stringify(dict);
    },


    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!hasPer.isPerShow(['showroom:art:edit'])) {
        return;
      }
      this.reset();
      this.title = "编辑商品";
      this.form = deepClone(row);
      this.form.isPutaway = String(this.form.isPutaway);
      // this.form.payType = String(this.form.payType);
      this.form.artVenues = Number(this.form.artVenues);
      this.open = true;
    },

    /** 提交按钮 */
    submitForm(refStr) {
      let ref = this.$refs[refStr];
      let valueData = ref.$refs.editor.currentValue;
      let params = ref.form;
      params.details = valueData;
      params.payType = 0;
      params.imgMin = params.minList;
      ref.$refs["form"].validate((valid) => {
        if (valid) {
          if (params.id != undefined) {
            editGoodsInfo(params).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodsInfo(params).then((response) => {
              this.$modal.msgSuccess("添加成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除商品编号为"' + row.goodsNo + '"的数据项？')
        .then(() => {
          delGoodsInfo({ goodsInfoId: row.id }).then((response) => {
            this.$modal.msgSuccess("删除成功");
            this.getList();
          });
        }
        ).catch(() => { });
    },

    /** 导出按钮操作 */
    exportExcel() {
      this.queryParams.beanName = 'GoodsInfoExport',
        this.queryParams.fileName = '竞价品',
        this.$alert('需要导出 "' + this.total + '" 条数据,是否确认导出', '提示', {
          confirmButtonText: '确定',

        }).then(() => {
          excelExportApi(this.queryParams, '/pms');
        });
    },
  },
};
</script>
<style scoped>
.el-dialog-div {
  height: 60vh;
  overflow: auto;
}
.input-W {
  width: 100%;
}
</style>
